import React, { useState, useMemo } from 'react';
import { Modal, Checkbox, Button, Space, message, Input, Tabs, Divider } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import { mergeReport } from '@/services/cpasRequest';

interface TableItem {
  tabName?: string;
  tabKey?: string;
  isVerify?: boolean;
  closable?: boolean;
  propsData?: {
    tableName: string;
    titleName: string;
    WscwbbType: string;
    origin: string;
    tabsIndex: number;
    actionCol?: number;
  };
  // 支持menu.json中的数据结构
  id?: string;
  title?: string;
  name?: string;
  associatedReport?: string;
  type?: string;
  category?: string; // 用于分类
}

interface TableSelectModalProps {
  visible: boolean;
  onCancel: () => void;
  onConfirm: (selectedTables: string[]) => void;
  tableData: TableItem[];
  companyTreeStructure: Array<{currentCompanyUscc: string, mergeType: number}>;
}

const TableSelectModal: React.FC<TableSelectModalProps> = ({
  visible,
  onCancel,
  onConfirm,
  tableData,
  companyTreeStructure,
}) => {
  const [selectedTables, setSelectedTables] = useState<string[]>([]);
  const [searchText, setSearchText] = useState<string>('');
  const [activeTab, setActiveTab] = useState<string>('all');

  // 获取表格名称的辅助函数
  const getTableName = (item: TableItem): string => {
    return item.propsData?.tableName || item.title || item.name || item.associatedReport || '';
  };

  // 获取表格唯一标识的辅助函数
  const getTableKey = (item: TableItem): string => {
    return item.tabKey || item.id || item.title || item.name || '';
  };

  // 分类和过滤数据
  const { categorizedData, filteredData } = useMemo(() => {
    // 按类别分组
    const categories: { [key: string]: TableItem[] } = {
      '审定财务': [],
      '资产类': [],
      '负债类': [],
      '损益类': [],
      '附注与分析': []
    };

    tableData.forEach(item => {
      const tableName = getTableName(item);
      if (item.propsData?.origin === '审定财务') {
        categories['审定财务'].push(item);
      } else if (item.propsData?.WscwbbType) {
        const type = item.propsData.WscwbbType;
        if (categories[type]) {
          categories[type].push(item);
        } else {
          categories['附注与分析'].push(item);
        }
      } else if (item.associatedReport) {
        // menu.json中的数据，根据名称进行简单分类
        if (tableName.includes('资产') || tableName.includes('货币') || tableName.includes('存货') || tableName.includes('投资')) {
          categories['资产类'].push(item);
        } else if (tableName.includes('负债') || tableName.includes('应付') || tableName.includes('借款')) {
          categories['负债类'].push(item);
        } else if (tableName.includes('收入') || tableName.includes('成本') || tableName.includes('费用') || tableName.includes('利润')) {
          categories['损益类'].push(item);
        } else {
          categories['附注与分析'].push(item);
        }
      } else {
        categories['附注与分析'].push(item);
      }
    });

    // 过滤搜索结果
    const filtered = tableData.filter(item => {
      const tableName = getTableName(item);
      const matchesSearch = tableName.toLowerCase().includes(searchText.toLowerCase());
      const matchesCategory = activeTab === 'all' || 
        (activeTab === '审定财务' && categories['审定财务'].includes(item)) ||
        (activeTab === '资产类' && categories['资产类'].includes(item)) ||
        (activeTab === '负债类' && categories['负债类'].includes(item)) ||
        (activeTab === '损益类' && categories['损益类'].includes(item)) ||
        (activeTab === '附注与分析' && categories['附注与分析'].includes(item));
      
      return matchesSearch && matchesCategory;
    });

    return { categorizedData: categories, filteredData: filtered };
  }, [tableData, searchText, activeTab]);

  const handleCheckboxChange = (tableName: string) => {
    setSelectedTables(prev => {
      if (prev.includes(tableName)) {
        return prev.filter(item => item !== tableName);
      } else {
        return [...prev, tableName];
      }
    });
  };

  const handleSelectAll = (e: CheckboxChangeEvent) => {
    if (e.target.checked) {
      const allTableNames = filteredData.map(item => getTableName(item));
      setSelectedTables(prev => [...new Set([...prev, ...allTableNames])]);
    } else {
      const filteredTableNames = filteredData.map(item => getTableName(item));
      setSelectedTables(prev => prev.filter(name => !filteredTableNames.includes(name)));
    }
  };

  const handleConfirm = async () => {
    try {
      const params = {
        tables: selectedTables,
        companyTreeStructure
      };
      
      await mergeReport(params);
      message.success('提交成功');
      onConfirm(selectedTables);
      setSelectedTables([]);
    } catch (error) {
      console.error('合并报表失败:', error);
      message.error('提交失败，请重试');
    }
  };

  const handleCancel = () => {
    setSelectedTables([]);
    onCancel();
  };

  const filteredTableNames = filteredData.map(item => getTableName(item));
  const isAllSelected = filteredTableNames.length > 0 && filteredTableNames.every(name => selectedTables.includes(name));
  const isIndeterminate = filteredTableNames.some(name => selectedTables.includes(name)) && !isAllSelected;

  // 标签页配置
  const tabItems = [
    { key: 'all', label: `全部 (${tableData.length})` },
    { key: '审定财务', label: `审定财务 (${categorizedData['审定财务'].length})` },
    { key: '资产类', label: `资产类 (${categorizedData['资产类'].length})` },
    { key: '负债类', label: `负债类 (${categorizedData['负债类'].length})` },
    { key: '损益类', label: `损益类 (${categorizedData['损益类'].length})` },
    { key: '附注与分析', label: `附注与分析 (${categorizedData['附注与分析'].length})` },
  ].filter(item => item.key === 'all' || categorizedData[item.key].length > 0);

  return (
    <Modal
      title="选择表格"
      open={visible}
      onCancel={handleCancel}
      footer={null}
      width={800}
      destroyOnClose
    >
      {/* 搜索框 */}
      <div style={{ marginBottom: 16 }}>
        <Input
          placeholder="搜索表格名称..."
          prefix={<SearchOutlined />}
          size='large'
          value={searchText}
          onChange={(e) => setSearchText(e.target.value)}
          allowClear
        />
      </div>

      {/* 分类标签页 */}
      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        items={tabItems}
        size="small"
        style={{ marginBottom: 16 }}
      />

      {/* 全选控制 */}
      <div style={{ marginBottom: 16 }}>
        <Checkbox
          indeterminate={isIndeterminate}
          onChange={handleSelectAll}
          checked={isAllSelected}
          disabled={filteredData.length === 0}
        >
          {activeTab === 'all' ? '全选当前筛选结果' : `全选${tabItems.find(t => t.key === activeTab)?.label || ''}`}
          {filteredData.length > 0 && ` (${filteredData.length}项)`}
        </Checkbox>
      </div>

      <Divider style={{ margin: '12px 0' }} />
      
      {/* 表格列表 */}
      <div style={{ maxHeight: 400, overflowY: 'auto', marginBottom: 16 }}>
        {filteredData.length === 0 ? (
          <div style={{ textAlign: 'center', color: '#999', padding: '40px 0' }}>
            {searchText ? '没有找到匹配的表格' : '该分类下暂无表格'}
          </div>
        ) : (
          <Space direction="vertical" style={{ width: '100%' }}>
            {filteredData.map((item) => {
              const tableName = getTableName(item);
              const tableKey = getTableKey(item);
              return (
                <Checkbox
                  key={tableKey}
                  checked={selectedTables.includes(tableName)}
                  onChange={() => handleCheckboxChange(tableName)}
                >
                  <div>
                    <div style={{ fontWeight: 500 }}>{tableName}</div>
                    {item.propsData?.titleName && (
                      <div style={{ fontSize: '12px', color: '#666', marginTop: '2px' }}>
                        {item.propsData.titleName}
                      </div>
                    )}
                  </div>
                </Checkbox>
              );
            })}
          </Space>
        )}
      </div>

      {/* 底部操作按钮 */}
      <div style={{ textAlign: 'right', borderTop: '1px solid #f0f0f0', paddingTop: '16px' }}>
        <Space>
          <div style={{ color: '#666', fontSize: '14px' }}>
            已选择 {selectedTables.length} 项
          </div>
          <Button onClick={handleCancel}>
            关闭
          </Button>
          <Button 
            type="primary" 
            onClick={handleConfirm}
            disabled={selectedTables.length === 0}
          >
            确认合并
          </Button>
        </Space>
      </div>
    </Modal>
  );
};

export default TableSelectModal;